var app = getApp()
import Poster from '../../poster-plugin/poster/poster';
const posterConfig = require('../../config/poster.js');
var WxParse = require('../../lib/wxParse/wxParse.js')
var Wxmlify = require('../../lib/wxmlify/wxmlify.js')
var util = require('../../utils/util.js')
var base64 = require('../../utils/base64.js')
var event = require('../../utils/event.js');
import {
  SoundPlayer
} from "../../utils/soundPlayer.js";
const date_util = require('../../utils/date_util.js')
var api = require('../../config/api.js')
var version = require('../../config/version.js')
var player = new SoundPlayer();
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
const myaudio = wx.createInnerAudioContext();
const posterActivityConfig = posterConfig.getPosterActivityCinfig();
const posterFeelingConfig = posterConfig.getPosterFeelingCinfig();
import ColorThief from '../../utils_color/color-thief.js'
import {
  rgbToHex,
  uuid,
  colorsEqual,
  saveBlendent,
  getPicColor
} from '../../utils_color/util.js'
//vipLevel  视频  文字 音频等icon图片
const picIcon = [
  'https://qn.simullink.com/FocVsylregOdmd8KFxagoOfkGa4y', 'https://qn.simullink.com/Fj1Bo9ne1iL9_c9FH86dUXqJMpe5',
  'https://qn.simullink.com/Fr1L8X6UPxcBOydhVSHD3sEniuWC', 'https://smtestopen.blcclb.com/FsDKjZP32Xifzg06K1QAn0yHToDY'
];
var loadMoreView, page;

Page({
  data: {
    posterSendConfig: posterActivityConfig.jdConfig,
    navigationBarHeight,
    statusBarHeight: app.statusBarHeight + 'px',
    id: 0,
    isIphoneX: app.globalData.isIphoneX ? true : false,
    myfollowacts: [],
    uuid: '',
    showPage: false,
    activityInfo: {},
    activityDetail: '',
    phValue: '表达感受...',
    comment_content: '',
    commentflag: false,
    commentId: '',
    commentIndex: 0,
    simulflag: false,
    userInfo: app.globalData.userInfo,
    auth: app.globalData.auth,
    systemInfo: {},
    hasUserInfo: app.globalData.hasUserInfo,
    hasPhone: app.globalData.hasPhone,
    // 父评论相关参数
    fatherComments: [],
    newFaList: [],
    fatherPage: 1,
    fatherSize: 10,
    ds: {},
    // 子评论相关参数
    sonComments: [],
    sonPage: 1,
    sonSize: 20,
    comment: [],
    simul: [],
    mycommentFaLocation: "bottom_mycommentFa",
    hiddenDelete: true,
    hiddenAll: true,
    hiddenShare: true,
    hiddenNavigation: true,
    hiddenWxShare: true,
    sharepicurl: '',
    shareImg: '',
    shareindex: -1,

    currentTab: 0,
    //处理视
    noPageScroll: false,
    videoContext: null,
    isPlay: false,
    //轮播相关
    faAutoplay: false,
    faIndicatorDots: false,
    //分享相关
    preIndex: 0,
    commId: 0, //分享过来的评论id
    source: 'index',

    scene: '',
    //标记扫码进入
    flag: 0,
    //选项卡效果
    curIndex: 0, //当前显示的view下标
    cur: 0,
    showUpload: true,
    showTitle: false,
    pagePadding: 0,
    float: false,
    marginWidth: 0
  },


  //视频播放与暂停
  // 点击播放按钮
  play: function() {
    if (this.data.isPlay) {
      this.setData({
        isPlay: false
      })
      this.videoContext.pause();
    } else {
      this.setData({
        isPlay: true
      })
      this.videoContext.play()
    }
  },

  // 开始播放
  bindPlay: function() {
    this.setData({
      isPlay: true
    })
  },

  // 暂停播放
  bindPause: function() {
    this.setData({
      isPlay: false
    })
  },

  // 播放完毕
  bindEnded: function() {
    this.setData({
      isPlay: false
    })
  },
  //视频时间更新
  timeupdate: function(e) {},


  //获取当前播放的是哪个评论
  onSlideChangeEnd: function(e) {
    var that = this;
    var current = e.detail.current
    if (e.detail.source == "touch") { //防止swiper控件卡死
      if (current == 0 && this.data.preIndex > 1) { //卡死时，重置current为正确索引        
        this.setData({
          curIndex: this.data.preIndex
        });
      } else { //正常轮转时，记录正确页码索引        
        this.setData({
          preIndex: current,
          curIndex: current
        });
      }
    }
    that.playComment(that, that.data.curIndex)
  },

  //解析扫码分享的参数
  getSharePara: function(id) {
    var that = this
    util.pututrequest(api.crackScene + '?scene=' + id, 'GET').then((res) => {
      if (res && res.code == 200) {
        res = res.data;
        that.setData({
          source: 'app',
          currentTab: res.type == 'FEELING' ? '1' : '0',
          // commId: res.comment_id,
          uuid: res.id,
          userInfo: app.globalData.userInfo,
          auth: app.globalData.auth,
          hasPhone: app.globalData.hasPhone,
        });
        that.getDetailInfo(that.data.uuid)
        that.getActivityDetail(that.data.uuid);
        that.getFatherComments(that.data.uuid, 1)
      }
    })
  },

  onPullDownRefresh() {
    var that = this
    page = 1
    wx.stopPullDownRefresh();
  },
  onReachBottom() {
    var that = this
    if (that.data.currentTab > 0 && that.data.fatherComments.length > 0) {
      if (!loadMoreView) {
        loadMoreView = that.selectComponent("#loadMoreView")
      }
      loadMoreView.loadMore()
    }

  },
  loadMoreListener: function(e) {
    var that = this
    // page += 1
    that.getFatherComments(that.data.uuid, 2)

  },
  clickLoadMore: function(e) {
    var that = this
    that.getFatherComments(that.data.uuid, 2)
  },

  onPageScroll: function(e) {
    var that = this
    let scrollTop = e.scrollTop;
    let tab = that.data.currentTab
    if (tab == 0) {
      if (scrollTop >= 493 && !this.data.showTitle) {
        that.setData({
          showTitle: true
        })
      } else if (scrollTop < 493 && this.data.showTitle) {
        that.setData({
          showTitle: false
        })
      }
    }
    if (tab == 1) {
      if (scrollTop >= 493 && !this.data.showTitle && that.data.fatherComments.length > 1) {
        that.setData({
          showTitle: true
        })
      } else if (scrollTop < 493 && this.data.showTitle) {
        that.setData({
          showTitle: false
        })
      }
    }
  },

  //新版改造
  onLoad: function(options) {
    page = 1
    var that = this;
    that.colorThief = new ColorThief('canvasidii');

    var uuid = ''; //活动id
    var commId = 0; //评论id 没有写0 
    var source = 'index'; //从app 或者其他页面
    var type = 0; //0 是活动  1是评论

    const scene = decodeURIComponent(options.scene)
    if ((typeof(scene) != undefined) && scene != 'undefined') { //扫码进入    
      that.setData({
        scene: scene
      })
      that.getSharePara(scene);
    } else {
      that.setData({
        flag: 1
      })
      uuid = options.uuid;
      commId = options.commId;
      source = options.source;
      type = options.type;
    }

    wx.showShareMenu({
      withShareTicket: true
    });

    // wx.hideShareMenu();

    that.setData({
      source: source,
      currentTab: type,
      commId: commId,
      uuid: uuid,
      userInfo: app.globalData.userInfo,
      hasUserInfo: app.globalData.hasUserInfo,
      auth: app.globalData.auth,
      hasPhone: app.globalData.hasPhone,
    });

    wx.getSystemInfo({
      success: function(res) {
        let w = res.windowWidth,
          h = res.windowHeight;
        let allHeight = that.data.fatherComments.length * (h);
        that.setData({
          winWidth: w,
          winHeight: h,
          systemInfo: res,
          marginWidth: (res.windowWidth - 166) / 2
        })
      },
    })
  },

  onMyevent: function(e) {
    var that = this
    that.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone,
    })
    if (that.data.auth && that.data.hasPhone) {
      that.getDetailInfo(that.data.uuid)
      that.getActivityDetail(that.data.uuid);
      event.emit('AuthChanged');
    }
  },
  launchAppError: function(e) {
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧！'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，请到AppStore里下载同感App查看更多同感动态！'
          })
        }
      }
    })
  },
  onReady: function() {
    var that = this
    that.videoContext = wx.createVideoContext('myVideo')
  },
  onShow: function() {
    loadMoreView = null
    if (this.data.flag > 0) {
      this.getDetailInfo(this.data.uuid)
      this.getFatherComments(this.data.uuid, 1)
      this.getActivityDetail(this.data.uuid);
    }
  },
  onHide: function() {},
  onUnload: function() {},
  //一、 详情页功能
  getDetailInfo: function(uuid) {
    var that = this;
    var followers = [];
    var i = 0;
    util.pututrequest(api.activityInfoMeta + '?activityId=' + uuid, 'GET').then((res) => {
      if (res && res.code == 200) {
        let venue = res.data.venue
        let activity = res.data.activity
        var begin = date_util.convertTime(activity.beginTime);
        var end = date_util.convertTime(activity.endTime);
        var title_str = util.mixTextOverflow(activity.name, 60)
        var title_title = util.mixTextOverflow(activity.name, 23)
        activity.venue = venue;
        activity.followers = res.data.followUsers;
        activity.begin = begin;
        activity.end = end;
        activity.title_str = title_str;
        activity.title_title = title_title;
        activity.area = venue ? (venue.name.length > 6 ? venue.name.substr(0, 5) + '...' : venue.name) : '';
        activity.acti_photo = activity.coverUrl
        activity.hasCollect = res.data.followed
        activity.collectCount = res.data.followUserCount
        that.setData({
          activityInfo: activity
        })

      }
    });

  },
  //  此方法由于json原因，单独请求，返回结果直接就是html
  getActivityDetail: function(uuid) {
    var that = this;
    wx.request({
      url: api.activityInfoDetail + '?activityId=' + uuid,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'accessToken': wx.getStorageSync('token'),
        'appVersion': version.appVersion,
        'deviceModel': getApp().globalData.systemInfo.model,
        'platform': 'wx',
        'build': version.build,
        'deviceMachineCode': '',
        'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
        'deviceOSVersion': getApp().globalData.systemInfo.system,
      },
      success: function(res) {
        that.setData({
          activityDetail: res.data
        })
      },
      fail: function(err) {}
    })
  },

  //1.地理位置导航
  intoMap: function() {
    var activityInfo = this.data.activityInfo
    if (activityInfo.venue) {
      wx.openLocation({
        latitude: Number(activityInfo.venue.latitude),
        longitude: Number(activityInfo.venue.longitude),
        name: activityInfo.venue.name,
        address: activityInfo.venue.name,
        scale: 16
      })
    }
  },
  // 返回上一页
  backhomepage: function() {
    var that = this;
    wx.switchTab({
      url: '/pages/index/index'
    });
    player.stop()
    let fatherComments = that.data.fatherComments
    for (var i = 0; i < fatherComments.length; i++) {
      fatherComments[i].bl = false;
    }
    that.setData({
      fatherComments: fatherComments
    })


  },
  gotoVideo: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index
    var item = that.data.fatherComments[index]
    var dir = that.data.ds[index]
    item.source = 'detail'
    let itemStr = JSON.stringify(item)
    let item64 = base64.encode(itemStr)
    let itemEncode = encodeURIComponent(item64)
    wx.navigateTo({
      url: '/pages/video/video?dataObj=' + itemEncode + '&uuid=' + this.data.activityInfo.id + '&title=' + this.data.activityInfo.name + '&pic=' + this.data.activityInfo.coverUrl + '&source=detail' + '&direction=' + dir,
      success: function() {},
      fail: function() {},
      complete: function() {}
    })
  },
  backhome: function() {
    var that = this;
    if (!that.data.source || that.data.source == 'index' || that.data.source == 'app' || that.data.source == 'upload' || typeof(that.data.source) == undefined) {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }

    if (that.data.source == 'follow') {
      wx.switchTab({
        url: '/pages/follow/follow'
      });
    }

    if (that.data.source == 'me') {
      wx.switchTab({
        url: '/pages/me/me'
      });
    }

    if (that.data.source == 'user') {
      wx.navigateBack({
        delta: 1
      })
    }

    player.stop()
    let fatherComments = that.data.fatherComments
    for (var i = 0; i < fatherComments.length; i++) {
      fatherComments[i].bl = false;
    }
    that.setData({
      fatherComments: fatherComments
    })
  },
  //2.关注
  follow: function(e) {
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      var fnew = that.data.activityInfo.followers
      fnew.push(app.globalData.userInfo)
      if (fnew.length > 3) {
        fnew.shift()
      }
      var followers = 'activityInfo.followers';
      var mefav = 'activityInfo.hasCollect';
      var countFllow = 'activityInfo.collectCount';
      var count = that.data.activityInfo.collectCount
      that.setData({
        [followers]: fnew,
        [mefav]: true,
        [countFllow]: count + 1,
      });

      util.pututrequest(api.collectActivity, 'POST', {
        id: this.data.uuid
      }).then(res => {
        if (res && res.code == 200) {
          that.setData({

          });
          //关注成功提示
          wx.showToast({
            title: '已加入“想去”',
            icon: 'success',
            duration: 2000
          })
          var newData = {};
          newData.data = that.data.activityInfo
          newData.action = 1
          event.emit('DataChanged', newData);
        }
      });

    } else {
      that.auth.showAuth();
    }
  },
  //3.取消关注
  cancelFollow: function(e) {
    util.pututrequest(api.collectActivity + '?id=' + this.data.uuid, 'DELETE').then(res => {
      if (res && res.code == 200) {
        let act_temp = this.data.activityInfo
        act_temp.hasCollect = false
        var fnew = this.data.activityInfo.followers
        var delId = 0
        var followers = 'activityInfo.followers';
        for (var i = 0; i < fnew.length; i++) {
          let oneFollow = fnew[i]
          if (oneFollow.id == app.globalData.userInfo.id) {
            delId = i
            break
          }
        }
        fnew.splice(delId, 1)
        var count = act_temp.collectCount
        act_temp.collectCount = count - 1
        this.setData({
          [followers]: fnew,
          activityInfo: act_temp
        })
        var newData = {};
        newData.data = this.data.activityInfo
        newData.action = -1
        event.emit('DataChanged', newData);
        wx.showToast({
          title: '我不想去啦',
          icon: 'success',
          duration: 2000
        })
      }
    })

  },

  tongGan: function(e) {
    let index = e.currentTarget.dataset.index
    let count = this.data.fatherComments[index].simul_count
    let photos = this.data.fatherComments[index].simul_photos
    let id = e.currentTarget.dataset.id
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      util.pututrequest(api.tongGan, 'POST', {
        activityId: that.data.uuid,
        feelingId: id
      }).then(res => {
        if (res && res.code == 200) {
          var tt = 'fatherComments[' + index + '].currentUserCollected'
          var ff = 'fatherComments[' + index + '].simul_count'
          var simul = 'fatherComments[' + index + '].simul_photos'

          var info = that.data.userInfo
          info["photo"] = info.avatarUrl
          photos.push(info)
          if (photos.length > 3) {
            photos.shift()
          }

          this.setData({
            [tt]: true,
            [ff]: count + 1,
            [simul]: photos,
          })
          wx.showToast({
            title: '深有同感',
            icon: 'success',
            duration: 2000
          })
        }
      })
    } else {
      that.auth.showAuth();
    }
  },

  cancelTongGan: function() {
    var that = this
    let index = that.data.shareindex
    let count = that.data.fatherComments[index].simul_count
    let photos = that.data.fatherComments[index].simul_photos
    let id = that.data.fatherComments[index].id
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      util.pututrequest(api.tongGan + '?feelingId=' + id, 'DELETE').then(res => {
        if (res && res.code == 200) {
          var tt = 'fatherComments[' + index + '].currentUserCollected'
          var ff = 'fatherComments[' + index + '].simul_count'
          var simul = 'fatherComments[' + index + '].simul_photos'

          var delId = 0
          for (var i = 0; i < photos.length; i++) {
            let oneFollow = photos[i]
            if (oneFollow.id == that.data.userInfo.id) {
              delId = i
              break
            }
          }
          photos.splice(delId, 1)

          this.setData({
            [tt]: false,
            [ff]: count - 1,
            [simul]: photos,
            hiddenDelete: true
          })
          wx.showToast({
            title: '取消同感',
            icon: 'success',
            duration: 2000
          })
        }
      })
    } else {
      that.auth.showAuth();
    }
  },
  deleteComment: function(e) {
    var that = this
    let index = e.currentTarget.dataset.index
    let id = e.currentTarget.dataset.id
    let fa = that.data.fatherComments
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      that.setData({
        hiddenDelete: false,
        shareindex: index
      })
    } else {
      that.auth.showAuth();
    }
  },
  deleteFeeling: function() {
    var that = this
    let fa = that.data.fatherComments
    let index = that.data.shareindex
    let feeling = fa[index]
    wx.showModal({
      title: '删除感受',
      content: '您确定删除这条感受吗？',
      showCancel: true, //是否显示取消按钮
      cancelText: "取消", //默认是“取消”
      cancelColor: '#0000FF',
      confirmText: "确定",
      confirmColor: '#DC143C', //确定文字的颜色
      success: function(ress) {
        if (ress.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          util.pututrequest(api.uploadTonggan + '?feelingId=' + feeling.id + '&activityId=' + that.data.activityInfo.id, 'DELETE').then(res => {
            if (res && res.code == 200) {
              fa.splice(index, 1)
              that.setData({
                fatherComments: fa,
                hiddenDelete: true,
              })
            }
          })
          //点击确定
        }
      },
      fail: function(ress) {}, //接口调用失败的回调函数
      complete: function(ress) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  // 分享活动
  // 处理分享海报
  updateActivityPosterConfig: function(isStart, bgColor, userInfo, activity, label, qrcode) {
    posterActivityConfig.jdConfig.backgroundColor = bgColor
    posterActivityConfig.jdConfig.images[0].url = userInfo.avatarUrl
    posterActivityConfig.jdConfig.images[1].url = activity.coverUrl
    posterActivityConfig.jdConfig.texts[0].text = userInfo.nickname
    posterActivityConfig.jdConfig.texts[1].text = activity.name
    posterActivityConfig.jdConfig.images[2].url = qrcode
    if (isStart) {
      if (posterActivityConfig.jdConfig.texts.length < 5) {
        posterActivityConfig.jdConfig.texts.splice(2, 0, {
          x: 672,
          y: 1225,
          baseLine: 'right',
          text: '18天',
          bold: true,
          fontSize: 32,
          width: 74,
          color: '#000000',
          zIndex: 100,
        });

        posterActivityConfig.jdConfig.texts.splice(4, 0, {
          x: 662,
          y: 1265,
          baseLine: 'right',
          width: 74,
          text: '倒计时',
          fontSize: 22,
          color: '#4A4A4A',
          zIndex: 100,
        });
      }
      posterActivityConfig.jdConfig.texts[2].text = activity.rest.day + '天'
      posterActivityConfig.jdConfig.texts[3].text = activity.area ? activity.area : ''
      posterActivityConfig.jdConfig.texts[4].text = label
      posterActivityConfig.jdConfig.texts[1].width = 400
    }

    if (!isStart) {
      if (posterActivityConfig.jdConfig.texts.length == 5) {
        posterActivityConfig.jdConfig.texts.splice(2, 1)
        posterActivityConfig.jdConfig.texts.splice(3, 1)
      }
      posterActivityConfig.jdConfig.texts[1].width = 500
      posterActivityConfig.jdConfig.texts[2].text = activity.area
    }
  },

  feelingFirstLineLocation: function(type, avatarUrl, nickname, viplevel, emoji) {
    posterFeelingConfig[type + 'Config'].images = []
    posterFeelingConfig[type + 'Config'].texts = []
    let len = 15,
      textStart = 120,
      jiange = 15;
    let textWidth = util.getTextLength(nickname) * len;
    posterFeelingConfig[type + 'Config'].images.push({
      width: 80,
      height: 80,
      x: 20,
      y: 30,
      borderRadius: 80,
      url: avatarUrl,
    })
    posterFeelingConfig[type + 'Config'].texts.push({
      x: textStart,
      y: 70,
      baseLine: 'middle',
      text: nickname,
      width: textWidth,
      fontSize: 32,
      color: '#000000',
    })
    if (viplevel > 0) {
      let kolStart = textStart + textWidth + jiange;
      posterFeelingConfig[type + 'Config'].images.push({
        width: 24,
        height: 24,
        x: kolStart,
        y: 58,
        borderRadius: 24,
        url: '',
      })
    }
    if (emoji) {
      let gandaoStart = textStart + textWidth + jiange;
      if (viplevel > 0) {
        gandaoStart = gandaoStart + 24 + jiange;
      }
      posterFeelingConfig[type + 'Config'].texts.push({ //感到
        x: gandaoStart,
        y: 70,
        baseLine: 'middle',
        text: '感到',
        width: 40,
        fontSize: 32,
        color: '#FF0000',
      })
      posterFeelingConfig[type + 'Config'].texts.push({ //表情
        x: gandaoStart + 60 + jiange,
        y: 70,
        baseLine: 'middle',
        text: emoji,
        fontSize: 32,
        color: '#000000',
      })
    }

  },

  updateFeelingPosterConfig: function(bgColor, feeling, qrcode) { //picIcon数组  feeling一条感受对象  qrcode二维码图片url
    this.feelingFirstLineLocation(feeling.type, feeling.user.avatarUrl, feeling.user.nickname, feeling.user.vipLevel, feeling.emotion)

    if (feeling.type == 'VIDEO') {
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.VIDEOConfig.images[1].url = picIcon[0]
      }
      posterFeelingConfig.VIDEOConfig.images.push({
        width: 630,
        height: 700,
        x: 20,
        y: 123,
        borderRadius: 40,
        url: feeling.thumbnail,
      })

      posterFeelingConfig.VIDEOConfig.texts.push({
        x: 20,
        y: 865,
        baseLine: 'left',
        text: feeling.content,
        width: 600,
        fontSize: 32,
        color: '#000000',
        zIndex: 100,
      })

      posterFeelingConfig.VIDEOConfig.images.push({ //play标记
        width: 50,
        height: 50,
        x: 320,
        y: 470,
        borderRadius: 50,
        url: picIcon[1],
      })

      posterFeelingConfig.VIDEOConfig.images.push({ //二维码
        width: 100,
        height: 100,
        x: 292,
        y: 940,
        borderRadius: 100,
        url: qrcode,
      })
    }


    if (feeling.type == 'IMAGE') {
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.IMAGEConfig.images[1].url = picIcon[0]
      }
      posterFeelingConfig.IMAGEConfig.images.push({
        width: 630,
        height: 700,
        x: 20,
        y: 123,
        borderRadius: 40,
        url: feeling.images_new[0].url,
      }, )

      posterFeelingConfig.IMAGEConfig.texts.push({
        x: 20,
        y: 865,
        baseLine: 'left',
        text: feeling.content,
        width: 600,
        fontSize: 32,
        color: '#000000',
        zIndex: 100,
      })
      posterFeelingConfig.IMAGEConfig.images.push({
        width: 100,
        height: 100,
        x: 292,
        y: 940,
        borderRadius: 100,
        url: qrcode,
      })
    }


    if (feeling.type == 'AUDIO') {
      posterFeelingConfig.AUDIOConfig.blocks[0].backgroundColor = bgColor
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.AUDIOConfig.images[1].url = picIcon[0]
      }
      posterFeelingConfig.AUDIOConfig.texts.push({
        x: 120,
        y: 480,
        baseLine: 'left',
        text: feeling.content,
        width: 400,
        fontSize: 32,
        color: '#fff',
        zIndex: 100,
      })

      posterFeelingConfig.AUDIOConfig.images.push({
        width: 450,
        height: 60,
        x: 110,
        y: 360,
        url: picIcon[1],
      })

      posterFeelingConfig.AUDIOConfig.images.push({
        width: 100,
        height: 100,
        x: 292,
        y: 860,
        borderRadius: 100,
        url: qrcode,
      })
    }

    if (feeling.type == 'TEXT') {
      posterFeelingConfig.TEXTConfig.blocks[0].backgroundColor = bgColor
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.TEXTConfig.images[1].url = picIcon[0]
      }

      posterFeelingConfig.TEXTConfig.texts.push({
        x: 120,
        y: 485,
        baseLine: 'left',
        text: feeling.content,
        width: 400,
        fontSize: 32,
        color: '#fff',
        zIndex: 100,
      })

      posterFeelingConfig.TEXTConfig.images.push({
        width: 50,
        height: 50,
        x: 110,
        y: 390,
        borderRadius: 50,
        url: picIcon[2],
      })

      posterFeelingConfig.TEXTConfig.images.push({
        width: 100,
        height: 100,
        x: 292,
        y: 880,
        borderRadius: 100,
        url: qrcode,
      })

    }

  },

  sharePic: function(e) {
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      if (that.data.currentTab > 0) {
        let index = e.currentTarget.dataset.index
        that.setData({
          shareindex: index
        })
      }
      that.setData({
        hiddenAll: false,
        hiddenNavigation: false,
        sharepicurl: ''
      })
    } else {
      that.auth.showAuth()
    }
  },

  close_share: function(e) {
    this.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true,
      hiddenAll: true,
      sharepicurl: ''
    })
    if (this.data.shareindex >= 0) {
      var act = this.data.fatherComments[this.data.shareindex]
      if (act.type == 'VIDEO') {
        this.setData({
          isPlay: true
        })
      }
      this.setData({
        shareindex: -1,
        sharepicurl: ''
      })
    }
  },

  generatePoster: function() {
    var that = this
    that.getSharePoster()
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: true
    })
  },
  saveWX: function() {
    var that = this
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  generateWXPoster: function() {
    var that = this
    that.getSharePoster()
    that.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  getSharePoster: function() {
    let that = this
    let type = 'ACTIVITY'
    var activityOrFeeling
    if (that.data.currentTab > 0 && that.data.shareindex > -1) {
      type = "FEELING"
    }
    if (type == 'ACTIVITY') {
      activityOrFeeling = that.data.activityInfo
      activityOrFeeling.rest = date_util.getRemainderTime(activityOrFeeling.beginTime)
    } else {
      activityOrFeeling = that.data.fatherComments[that.data.shareindex]
    }

    wx.showLoading({
      title: '生成海报...',
      mask: true,
    })
    util.pututrequest(api.generateQrcode, 'POST', {
      id: activityOrFeeling.id,
      type: type
    }).then(res => {
      if (res && res.code == 200) {
        let qrcode = res.data.url
        if (qrcode) {
          if (type == 'ACTIVITY') {
            const imagePath = activityOrFeeling.coverUrl
            getPicColor(imagePath, that.colorThief).then(res => {
              var timestamp = new Date().getTime()
              if (that.data.activityInfo.beginTime > timestamp) {
                that.updateActivityPosterConfig(true, res, that.data.userInfo, activityOrFeeling, '倒计时', qrcode)
              } else {
                that.updateActivityPosterConfig(false, res, that.data.userInfo, activityOrFeeling, '', qrcode)
              }
              this.setData({
                posterSendConfig: posterActivityConfig.jdConfig
              }, () => {
                Poster.create(true); // 入参：true为抹掉重新生成 
              });
            })
          }

          if (type == 'FEELING') {
            if (activityOrFeeling.type == 'AUDIO' || activityOrFeeling.type == 'TEXT') {
              const imagePath = that.data.activityInfo.coverUrl
              getPicColor(imagePath, that.colorThief).then(res => {
                that.updateFeelingPosterConfig(res, activityOrFeeling, qrcode)
                this.setData({
                  posterSendConfig: posterFeelingConfig[activityOrFeeling.type + 'Config']
                }, () => {
                  Poster.create(true); // 入参：true为抹掉重新生成 
                });
              })

            } else {
              that.updateFeelingPosterConfig('', activityOrFeeling, qrcode)
              this.setData({
                posterSendConfig: posterFeelingConfig[activityOrFeeling.type + 'Config']
              }, () => {
                Poster.create(true); // 入参：true为抹掉重新生成 
              });
            }

          }

        } else {
          wx.showModal({
            title: '二维码获取失败',
            showCancel: false,
            content: '该活动海报的二维码获取失败,请重新生成！'
          })
        }

      }
    });
  },

  onPosterSuccess(e) {
    const {
      detail
    } = e;
    this.setData({
      hiddenShare: false,
      sharepicurl: detail
    })
    wx.hideLoading()
  },
  onPosterFail(err) {
    console.error(err);
  },

  saveNetPicToLocal: function() {
    console.log('开始保存')
    let that = this
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    //图片保存到本地
    wx.saveImageToPhotosAlbum({
      filePath: that.data.sharepicurl,
      success: function(data) {
        wx.showModal({
          title: '保存成功',
          content: '活动海报保存到相册成功',
          confirmText: "我知道了",
          showCancel: false,
        })
      },
      fail: function(err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.openSetting({
            success(settingdata) {
              if (settingdata.authSetting['scope.writePhotosAlbum']) {
                wx.showToast({
                  title: '授权成功，继续保存',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: '未授权，无法保存',
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        }
      },
    })
    wx.hideLoading()
  },


  cancleMask: function() {
    this.setData({
      commentflag: false,
      simulflag: false,
      showUpload: true,
      hiddenAll: true,
      hiddenDelete: true,
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true,
      sharepicurl: ''
    })
  },

  //右上角转发事件
  rightShare: function() {
    var that = this
    that.showLoadTip()
    var comment = that.data.fatherComments[that.data.curIndex]
    util.pututrequest(api.generateSharePic + '?uuid=' + comment.id + '&type=COMMENT', 'GET').then(res => {
      if (res && res.code == 200) {
        wx.hideLoading()
        that.setData({
          shareImg: res.data.path,
        })
      }
    })
  },



  onShareAppMessage: function(ops) {
    var that = this
    var index = 0
    var img = ''
    if (ops.from === 'button') { //页面内转发按钮      
      index = this.data.shareindex
    } else {
      index = this.data.curIndex
    }
    //判断分享评论
    if (this.data.currentTab > 0 && this.data.fatherComments.length != 0) {
      var act = this.data.fatherComments[index]
      var shareText = ""
      if (act.content && act.content != '') {
        shareText = act.content
      } else {
        shareText = this.data.activityInfo.name
      }

      return {
        title: shareText,
        desc: shareText,
        path: '/pages/share/share?uuid=' + this.data.activityInfo.id + '&source=app&commId=' + act.id + '&type=1',
        imageUrl: that.data.sharepicurl,
        success: function(res) { // 转发成功       
          var shareTickets = res.shareTickets;
          if (shareTickets.length == 0) {
            return false;
          }
          //可以获取群组信息
          if (this.data.systemInfo.platform == 'android' && (shareTickets.length > 0)) {
            wx.getShareInfo({
              shareTicket: shareTickets[0],
              success: function(res) {
                wx.showToast({
                  title: "分享成功",
                  duration: 2000
                });
              },
              fail: function() {
                wx.showToast({
                  title: "分享失败",
                  duration: 2000
                });
              }
            })
          }
          if (this.data.systemInfo.platform == 'ios' && (shareTickets.length > 0)) {
            wx.showToast({
              title: "分享成功",
              duration: 2000
            });
          }
        },
        fail: function(res) { // 转发失败        
          wx.showToast({
            title: "分享失败，请重新分享",
            duration: 2000
          });
        }
      }
    } else {
      var act = this.data.activityInfo
      return {
        title: act.begin.monthOri + '-' + act.begin.dayOri + '•' + act.area + '\n' + act.name,
        desc: act.name,
        path: '/pages/detail/detail?uuid=' + act.id + '&source=app&commId=0&type=0',
        imageUrl: this.data.sharepicurl ? this.data.sharepicurl : act.acti_photo,
        success: function(res) { // 转发成功       
          var shareTickets = res.shareTickets;
          if (shareTickets.length == 0) {
            return false;
          }
          //可以获取群组信息
          if (this.data.systemInfo.platform == 'android' && (shareTickets.length > 0)) {
            wx.getShareInfo({
              shareTicket: shareTickets[0],
              success: function(res) {
                wx.showToast({
                  title: "分享成功",
                  duration: 2000
                });
              },
              fail: function() {
                wx.showToast({
                  title: "分享失败",
                  duration: 2000
                });
              }
            })
          }
          if (this.data.systemInfo.platform == 'ios' && (shareTickets.length > 0)) {
            wx.showToast({
              title: "分享成功",
              duration: 2000
            });
          }
        },
        fail: function(res) { // 转发失败        
          wx.showToast({
            title: "分享失败，请重新分享",
            duration: 2000
          });
        }
      }
    }
    //11
  },

  videoTip: function() {
    wx.showModal({
      title: '友情提示',
      content: '想看完整视频，请下载同感App',
      confirmText: "我知道了",
      showCancel: false,
    })
  },


  //判断当前评论类型，如果视频 音频 播放
  playComment: function(that, curIndex) {
    that.setData({
      cur: 1
    })
    that.setData({
      cur: 0
    })
    player.stop()
    if (that.data.fatherComments.length > 0) {
      let type = that.data.fatherComments[curIndex]
      if (type.type == "AUDIO" && that.data.currentTab == 1) {
        let fatherComments = that.data.fatherComments,
          vidSrc = fatherComments[curIndex].path;
        for (var i = 0; i < fatherComments.length; i++) {
          fatherComments[i].bl = false;
        }
        fatherComments[curIndex].bl = true;
        that.setData({
          fatherComments: fatherComments
        })
        player.play(vidSrc, () => {});

      }

      if (type.type != "AUDIO") {
        player.stop()
        let fatherComments = that.data.fatherComments
        for (var i = 0; i < fatherComments.length; i++) {
          fatherComments[i].bl = false;
        }
        that.setData({
          fatherComments: fatherComments
        })
      }

    }

  },
  //二、 详情页现场功能
  changeFinish: function(event) {
    var currentIndex = event.detail.current
    //上拉刷新
    if (currentIndex == 0 && this.data.preIndex != 0) {
      this.refresh()
    }
    //加载更多
    if (currentIndex >= this.data.fatherComments.length - 1) {
      this.bindDownLoad()
    }
    this.setData({
      preIndex: currentIndex
    })
  },
  bindDownLoad: function() {
    var that = this;
    that.showLoadTip()
    that.getFatherComments(this.data.uuid, 2);
  },

  refresh: function(event) {
    this.setData({
      fatherPage: 1,
      scrollTop: 0
    });
    this.getFatherComments(this.data.uuid, 1)
  },
  // 1.获取活动的父评论
  showLoadTip: function() {
    wx.showLoading({
      title: '正在加载中...',
      mask: true
    })
  },
  folded_change: function(e) {
    var that = this
    let index = e.currentTarget.dataset.index
    let t = that.data.fatherComments[index].isFolded
    let tt = 'fatherComments[' + index + '].isFolded'
    that.setData({
      [tt]: !t
    })
  },
  getFatherComments: function(uuid, type) {
    var that = this;
    var last_content = null;
    var lastId = ""
    var lastTimestamp = 0
    var requestUrl = api.feelingList + '?activityId=' + uuid
    if (type > 1) {
      last_content = that.data.fatherComments[that.data.fatherComments.length - 1]
      lastId = last_content.id
      lastTimestamp = last_content.createTime
      requestUrl = requestUrl + '&lastId=' + lastId + '&lastTimestamp=' + lastTimestamp
    }
    util.pututrequest(requestUrl, 'GET').then((res) => {
      if (res && res.code == 200) {
        if (res.data) {
          var orifatherCom = res.data
          var orifatherComNew = []
          for (var i = 0; i < orifatherCom.length; i++) { //3
            var feeling = orifatherCom[i].feeling
            var user = orifatherCom[i].user
            var simulUsers = orifatherCom[i].simulUsers
            feeling.nickname = util.mixTextOverflow(user.nickname, 14)
            feeling.isFolded = true
            feeling.photoPath = user.avatarUrl
            feeling.simul_photos = simulUsers
            feeling.simul_count = orifatherCom[i].simulCount
            feeling.comment_count = orifatherCom[i].commentCount
            feeling.currentUserCollected = orifatherCom[i].isSimul
            feeling.user = user

            if (feeling.type == "VIDEO") {
              let feelingMedia = feeling.media && feeling.media.length > 0 ? feeling.media[0] : {}
              feeling.thumbnail = ''
              if (feelingMedia && JSON.stringify(feelingMedia) != "{}") {
                feeling.thumbnail = feelingMedia.thumbnailUrl + "?imageView2/0/h/668/format/jpg"
              }
            }

            if (feeling.type == "AUDIO") {
              let feelingMedia = feeling.media && feeling.media.length > 0 ? feeling.media[0] : {}
              feeling.thumbnail = ''
              if (feelingMedia && JSON.stringify(feelingMedia) != "{}") {
                feeling.path = feelingMedia.url
              }
            }

            if (feeling.type == "IMAGE") { //image
              let feelingMedias = feeling.media && feeling.media.length > 0 ? feeling.media : []
              let picArray = []
              for (var j = 0; j < feelingMedias.length; j++) {
                var oneMedia = feelingMedias[j]
                var url = '',
                  url_src = '';
                url_src = oneMedia.thumbnailUrl
                url = oneMedia.thumbnailUrl +
                  "?imageView2/0/h/668/format/jpg"
                picArray.push({
                  'direction': 'shu',
                  'url': url,
                  'url_src': url_src
                })
              }
              feeling.images_new = picArray
            } // image

            feeling.txtheight = 'txt_normal'
            feeling.bl = false
            orifatherComNew.push(feeling)
          } //3 

          var items = that.data.fatherComments
          if (type == 1) {
            items = orifatherComNew
            wx.stopPullDownRefresh()
          } else {
            items = items.concat(orifatherComNew)
          }
          that.setData({
            fatherComments: items,
            showPage: true,
          })
        } else {
          that.setData({
            showPage: true,
          })
        }
        var tt = res.data
        let moreres = false
        if (tt && tt.length >= 20) {
          moreres = true
        }

        if (loadMoreView) {
          loadMoreView.loadMoreComplete(moreres)
        } else {
          loadMoreView = that.selectComponent("#loadMoreView")
          if (loadMoreView) {
            loadMoreView.loadMoreComplete(moreres)
          }

        }
      }
    });
  },
  changeTxtHeight: function(e) {
    var that = this;
    let faindex = e.currentTarget.dataset.faindex
    var item = that.data.fatherComments[faindex]
    if (item.type == 'IMAGE' || item.type == 'VIDEO') {
      var txtHeight = 'fatherComments[' + faindex + '].txtheight'
      if (item.txtheight == 'txt_normal') {
        that.setData({
          [txtHeight]: 'txt_all'
        })
      } else {
        that.setData({
          [txtHeight]: 'txt_normal'
        })
      }
    }
  },
  thumbnailLoad: function(e) {
    var that = this;
    var dss = that.data.ds
    let faindex = e.currentTarget.dataset.faindex
    var item = that.data.fatherComments[faindex]
    let dir = ''

    let originalWidth = e.detail.width;
    let originalHeight = e.detail.height;
    if (originalWidth > originalHeight) {
      dir = 'heng'
    } else {
      dir = 'shu'
    }

    var valueset = 'fatherComments[' + faindex + '].direction';
    dss[faindex] = dir
    this.setData({
      [valueset]: dir,
      ds: dss
    })

  },
  imageLoad: function(e) { //获取图片的原始宽度和高度
    let sonindex = e.currentTarget.dataset.sonindex
    let faindex = e.currentTarget.dataset.faindex
    let originalWidth = e.detail.width;
    let originalHeight = e.detail.height;
    let dir = ''
    if (originalWidth > originalHeight) {
      dir = 'heng'
    } else {
      dir = 'shu'
    }
    var valueset = 'fatherComments[' + faindex + '].images_new[' + sonindex + '].direction';
    this.setData({
      [valueset]: dir
    })
  },
  //2. 获取子评论
  getComments: function(e) {
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    var that = this;
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      var act = that.data.fatherComments[index]
      if (act.type == "VIDEO") {
        that.setData({
          isPlay: false
        })
      }
      that.setData({
        comment: [],
        showUpload: false,
      })

      var last_content = null;
      var lastId = ""
      var lastTimestamp = 0
      var requestUrl = api.commentList + '?activityId=' + that.data.uuid + '&feelingId=' + id
      if (that.data.comment && that.data.comment.length > 0) {
        last_content = that.data.comment[that.data.comment.length - 1]
        lastId = last_content.id
        lastTimestamp = last_content.createTime
        requestUrl = requestUrl + '&lastId=' + lastId + '&lastTimestamp=' + lastTimestamp
      }

      util.pututrequest(requestUrl, 'GET').then((res) => {
        if (res && res.code == 200) {
          this.setData({
            commentflag: true,
            commentId: id,
            commentIndex: index,
          })
          var tt = res.data.comments;
          if (tt) {
            for (let i = 0; i < tt.length; i++) {
              tt[i].to_now = date_util.getToNow(tt[i].createTime)
              if (tt[i].user) {
                if (tt[i].user.avatarUrl) {
                  tt[i].user.photo = tt[i].user.avatarUrl
                } else {
                  tt[i].user.photo = 'http://simul.dpaper.cn/miniprogram/images/index/photo.jpeg'
                }
              }
              this.setData({
                comment: tt,
              })
            }
          }
        }

      })
    } else {
      that.auth.showAuth()
    }
  },
  // 2.1 评论框焦点
  onFocus: function(e) {
    this.setData({
      phValue: " ",

    })
  },
  // 2.2 评论框失去焦点
  // onBlur: function(e) {
  //   this.setData({})
  // },
  // 2.3 评论框输入
  commentInput: function(e) {
    this.setData({
      comment_content: e.detail.value
    })
  },
  // 2.4 发送子评论
  sendComment: function(e) {
    var that = this;
    var comm = e.currentTarget.dataset.comm
    var count = this.data.fatherComments[this.data.commentIndex].comment_count
    if (comm == '' || comm == null) {
      wx.showToast({
        title: '请输入评论内容!',
        icon: 'success',
        duration: 2000
      })
      return;
    }
    var commArry = []
    if (that.data.comment.length > 0) {
      commArry = that.data.comment
      commArry.unshift({
        "id": 1900,
        "to_now": '刚刚',
        "user": {
          "nickname": app.globalData.userInfo.nickname,
          "photo": that.data.userInfo.avatarUrl,
        },
        "content": comm
      })
    } else {
      commArry.push({
        "id": 1900,
        "to_now": '刚刚',
        "user": {
          "nickname": app.globalData.userInfo.nickname,
          "photo": that.data.userInfo.avatarUrl,
        },
        "content": comm
      })
    }

    this.setData({
      comment: commArry,
    })
    util.pututrequest(api.comment, 'POST', {
      feelingId: that.data.commentId,
      content: comm,
      activityId: that.data.uuid
    }).then((res) => {
      if (res && res.code == 200) {
        var tt = 'fatherComments[' + this.data.commentIndex + '].comment_count'
        wx.showToast({
          title: '评论成功!',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          phValue: "表达感受...",
          comment_content: '',
          [tt]: count + 1,

        })
      }
    })
  },
  click_blank: function(e) {
    this.setData({
      commentflag: false,
      simulflag: false,
      hiddenShare: true,
      commentId: '',
      showUpload: true,
    })
  },

  /**
   * 滑动切换tab
   */
  bindChange: function(e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
    that.playComment(that, that.data.curIndex)

  },
  /**
   * 点击tab切换
   */
  swichNav: function(e) {
    var that = this;
    if (that.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
      page = 1
      loadMoreView = null
      if (that.data.currentTab > 0) {
        that.getFatherComments(that.data.uuid, 1)
      } else {
        that.getDetailInfo(that.data.uuid)
        that.getActivityDetail(that.data.uuid);
      }
    }
  },

  // 播放音频
  audioPlay: function(e) {
    var that = this,
      id = e.currentTarget.dataset.id,
      key = e.currentTarget.dataset.key,
      fatherComments = that.data.fatherComments;
    var vidSrc = fatherComments[key].path;

    for (var i = 0; i < fatherComments.length; i++) {
      fatherComments[i].bl = false;
    }
    fatherComments[key].bl = true;
    that.setData({
      fatherComments: fatherComments
    })
    player.play(vidSrc, () => {
      //播放完成回调
    });
  },
  // 停止音频
  audioStop: function(e) {
    var that = this,
      key = e.currentTarget.dataset.key,
      fatherComments = that.data.fatherComments;
    //切换显示状态
    for (var i = 0; i < fatherComments.length; i++) {
      fatherComments[i].bl = false;
    }
    that.setData({
      fatherComments: fatherComments
    })
    player.stop()
  },

  // 点击视频播放
  eventPlay(event) {
    const {
      index
    } = event.currentTarget.dataset
    this.showVideoList(index)
  },

  showVideoList(index) {
    var fas = this.data.fatherComments
    for (var i = 0; i < fas.length; i++) {
      fas[i].bl = false;
    }
    if (index >= 0 && this.data.fatherComments[index]) {
      var tt = "fatherComments[" + index + "].bl"
      this.setData({
        [tt]: true
      })
    }
  },
  gotoUser: function(e) {
    player.stop()
    var that = this
    var faComm = that.data.fatherComments
    var index = e.currentTarget.dataset.userindex
    var user = faComm[index].user
    if (user) {
      var userStr = JSON.stringify(user);
      var user64 = base64.encode(userStr);
      var userEncode = encodeURIComponent(user64);

      wx.navigateTo({
        url: '/pages/user/user?userObj=' + userEncode,
        success: function() {},
        fail: function() {},
        complete: function() {}
      })

    } else {
      wx.showModal({
        title: '错误提示',
        content: '该用户在本产品中走丢了，我们正在找回他（她）',
        confirmText: "我知道了",
        showCancel: false,
      })
    }
  },

  gotoSimulUser: function(e) {
    player.stop()
    var that = this
    var item = e.currentTarget.dataset.item
    var user = item.user
    if (user) {
      var userStr = JSON.stringify(user);
      var user64 = base64.encode(userStr);
      var userEncode = encodeURIComponent(user64);

      wx.navigateTo({
        url: '/pages/user/user?userObj=' + userEncode,
        success: function() {},
        fail: function() {},
        complete: function() {}
      })

    } else {
      wx.showModal({
        title: '错误提示',
        content: '该用户在本产品中走丢了，我们正在找回他（她）',
        confirmText: "我知道了",
        showCancel: false,
      })
    }
  },

  showSimul: function(e) {
    var that = this
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人,很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧!'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人,请到AppStore里下载同感App查看更多同感动态!'
          })
        }
      }
    })
  },
  // 上传
  goUpload: function(e) {
    player.stop()
    var that = this;
    let itemStr = JSON.stringify(that.data.activityInfo)
    let item64 = base64.encode(itemStr)
    let itemEncode = encodeURIComponent(item64)
    var timestamp = new Date().getTime()
    if ((that.data.activityInfo.beginTime - 1000 * 60 * 30) > timestamp) {

      wx.showModal({
        title: '温馨提示',
        content: '活动尚未开始，不如去和小伙伴们分享你去过的现场吧',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/search/search',
              success: function() {},
              fail: function() {},
              complete: function() {}
            })
          }
        }
      })

    } else {
      let tokenValue = wx.getStorageSync('token')
      let userInfoValue = wx.getStorageSync('userInfo');

      if (userInfoValue && JSON.stringify(userInfoValue) != "{}" && tokenValue && tokenValue != '') {
        that.setData({
          userInfo: userInfoValue,
          auth: true,
          hasPhone: app.globalData.hasPhone
        })
        // 业务
        wx.navigateTo({
          url: '/pages/upload/upload?dataObj=' + itemEncode,
          success: function() {},
          fail: function() {},
          complete: function() {}
        })
        // 业务
      } else {
        // 权限控制
        that.auth = that.selectComponent("#auth");
        util.getScope('scope.userInfo').then(function(resss) {
          if (resss) {
            that.auth.hideAuth();
            ///防止緩存失效带来的问题
            let code = null;
            return that.login().then((res) => { //userInfo
              code = res.code;
              wx.getUserInfo({
                withCredentials: true,
                success: function(res_user) {
                  //先去登陆        
                  wx.request({
                    url: api.userAuth,
                    data: {
                      platform: 'wx',
                      authorizationCode: code,
                      userEncryptrfData: res_user.encryptedData,
                      iv: res_user.iv
                    },
                    method: 'POST',
                    header: {
                      'Content-Type': 'application/json',
                      'accessToken': wx.getStorageSync('token'),
                      'appVersion': version.appVersion,
                      'deviceModel': getApp().globalData.systemInfo.model,
                      'platform': 'wx',
                      'build': version.build,
                      'deviceMachineCode': '',
                      'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                      'deviceOSVersion': getApp().globalData.systemInfo.system,
                    },
                    success: function(res) {
                      if (res && res.statusCode == 200 && res.data.code == 200) {
                        wx.setStorageSync('token', res.data.data.token);
                        app.globalData.token = res.data.data.token;
                        var userInfo = res.data.data.user
                        if (userInfo && !userInfo.avatarUrl) {
                          userInfo.avatarUrl = version.defaultAvataUrl
                        }
                        wx.setStorageSync('userInfo', userInfo);
                        app.globalData.userInfo = userInfo
                        app.globalData.hasUserInfo = true
                        app.globalData.auth = true
                        app.globalData.hasPhone = true
                        wx.setStorageSync('hasPhone', true);
                        wx.setStorageSync('auth', true);
                        app.globalData.hasPhone = false
                        wx.setStorageSync('hasPhone', false);
                        that.setData({
                          auth: true,
                          hasUserInfo:true,
                          userInfo: app.globalData.userInfo,
                          hasPhone: app.globalData.hasPhone,
                        });
                        // 业务
                        wx.navigateTo({
                          url: '/pages/upload/upload?dataObj=' + itemEncode,
                          success: function() {},
                          fail: function() {},
                          complete: function() {}
                        })
                        // 业务
                      }
                      if (res && res.data.code == 301) {
                        wx.setStorageSync('token', res.data.data.token);
                        app.globalData.token = res.data.data.token;
                        app.globalData.hasPhone = false
                        wx.setStorageSync('hasPhone', false);
                      } 
                    }
                  })
                }
              })
            })
            //防止緩存失效带来的问题         
          } else {
            that.auth.showAuth();
          }
        })
      } //else
    }

  },
  actionHandle: function() {

  },


  login: function() {
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            //登录远程服务器
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },
  // 图片预览
  previewImage: function(e) {
    var that = this
    var current = e.target.dataset.src;
    var allImages = e.target.dataset.all;
    const imgList = allImages.map(function(value, index, array) {
      return value.url_src
    })
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: imgList // 需要预览的图片http链接列表  
    })
  },

})